package br.com.passeionaweb.appengine.tabelafipe.data;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable
public class Year {
	public static String KEY_YEAR = "year";

	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Long id;

	public Long getId() {
		return id;
	}

	@Persistent
	private String year;

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public Year(String year) {
		super();
		this.year = year;
	}

	static public boolean exists(String year) {
		return getYear(year) != null;
	}

	static public Year getYear(String year) {
		try {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(Year.class);
			query.setFilter("year == param_year");
			query.declareParameters("String param_year");
			List<Year> years = (List<Year>) query.execute(year);
			if (years.isEmpty()) {
				return null;
			} else {
				return years.get(0);
			}
		} catch (Exception e) {
			return null;
		}
	}

	static public Year getYear(long yearid) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		return pm.getObjectById(Year.class, yearid);
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj == null|| !(obj instanceof Year)){
			return false;
		}else if(((Year)obj).getYear().equals(year)){
			return true;
		}else{
			return super.equals(obj);
		}
	}
	
	@Override
	public String toString() {
		return year;
	}
}
